<?php
require_once 'userClass.php';
require_once 'include/siteConfig.php';


/**
 * Dont know why this is here ? and not in a class
 * @param object $db
 * @param int $themeID
 */
function getUserThemeList($db, $themeID){
	//TODO make user able to choose theme on each post
	$query = "SELECT * FROM theme";
	$result = $db -> prepare($query);
	$result -> execute();
	foreach($result as $theme){
		echo "<option value='{$theme['id']}'";
		if($theme['id'] == $themeID){
			echo "selected";
		}			
		echo ">{$theme['themeName']}</option>";
	}
}

/**
 * Get all not blocked users for the new admin form
 * @param object $db
 */

function getUserList($db){
	//TODO make user able to choose theme on each post
	$query = "SELECT userID, userName FROM user
				WHERE isBlocked NOT LIKE 1 AND isAdmin NOT LIKE 1";
	$result = $db -> prepare($query);
	$result -> execute();
	foreach($result as $user){
		echo "<option value='{$user['userID']}'";
		echo ">{$user['userName']}</option>";
	}
}


function fbButtonJsScript(){
	echo "<div id='fb-root'></div>
	  <script>(function(d, s, id) {			
	  var js, fjs = d.getElementsByTagName(s)[0];
	  if (d.getElementById(id)) return;
	  js = d.createElement(s); js.id = id;
	  js.src = '//connect.facebook.net/en_GB/all.js#xfbml=1&appId=1409036512680858';
	  fjs.parentNode.insertBefore(js, fjs);
	}(document, 'script', 'facebook-jssdk'));</script>";
}

function fbLikeBtn($type){
	if($type != 'like'){
		echo "<div class='fb-like' 
			data-href='https://www.nerfuxzone.net/ebbs' 
			data-width='300' data-layout='standard' data-action='recommend' data-show-faces='true' 
			data-share='true'></div>";
	}else{
		echo "<div class='fb-like' 
			data-href='https://www.nerfuxzone.net/ebbs'
			data-width='300' data-layout='standard' data-action='like' data-show-faces='true'
			data-share='true'></div>";
	}
}
	/**
	 * Count number of views on a site
	 * Writen from http://www.free-php-counter.com/
	 * to use PDO, and couning more than one site at the time
	 * using views to calculate right data.
	 * @author divparken@gmail.com
	 * @param obj $db PDO
	 * @throws Exception If insert fails
	 */
function countVisits($db){
	// Options & Settings
	// Ip-protection in seconds
	$counter_expire = $conf_expire;	
	// Ignore Agent List
	$counter_ignore_agents = $conf_ignore_agents;
	// Ignore Ip List
	$counter_ignore_ips = $conf_ignore_ips;	
	// Ignore Sites
	$count_ignore_sites = $conf_ignore_sites;
	// Gather Basic Information
	$counter_agent = $_SERVER['HTTP_USER_AGENT'];
	$counter_ip = $_SERVER['REMOTE_ADDR'];
	$site = htmlspecialchars(strtolower(strrchr($_SERVER['REQUEST_URI'], "/")));
	$counter_time = time();	
	$counter_connected = true;
	$ignore = false;
	
	// Get count information
	$sql = "SELECT * FROM counter_values 
			WHERE site=:site AND concat_ws('-', year_id, month_id, day_id) = curdate()";
	$res = $db -> prepare($sql);
	$res -> bindParam(":site", $site);
	$res -> execute ();
	$infoToday = $res -> fetch();
	if(isset($infoToday['year_id'])){
		$sql = "SELECT view_getCounter.*, sum(counter_values.all_value) as all_value
			FROM view_getCounter LEFT JOIN counter_values ON view_getCounter.site = counter_values.site 
	    	WHERE view_getCounter.site=:site";
		$res = $db -> prepare($sql);
		$res -> bindParam(":site", $site);
		$res -> execute ();
		$statsInfo = $res -> fetch();
	}else{
		// Fill when table is empty/never visited!
		$res -> closeCursor();
		$sql = "INSERT INTO counter_values 
				(site, day_id, day_value, month_id, year_id, all_value, record_date, record_value) 
				values ( :site, :thisDayOfMonth,  '1', :numberOfMonth, :year,  '1',  
				(CASE WHEN (Select record_date from view_getCounter where site=:site AND 
					(select Max(record_date) from view_getCounter where site=:site)) = NULL
				THEN 
					(select Max(record_date) from view_getCounter where site=:site) 
				 ELSE 
					now()
				END),
				(CASE WHEN (Select recordInOneDay from view_getCounter where site=:site AND 
					(select Max(recordInOneDay) from view_getCounter where site=:site)) = NULL
				THEN  
					(select Max(recordInOneDay) from view_getCounter where site=:site) 
				ELSE 
					'1' 
				END))";
		$res = $db -> prepare($sql);
		$res -> bindParam(":site", $site);
		$date = array(date("j"), date("n"), date("Y"));
		$res -> bindParam(":thisDayOfMonth", $date[0]);
		$res -> bindParam(":numberOfMonth", $date[1]);
 		$res -> bindParam(":year", $date[2]);
		$res -> execute();	
		$res -> closeCursor();
		
		// Reload with the inserted info into variable
		$sql = "SELECT * FROM counter_values WHERE site=:site AND CONCAT_WS('-',year_id, month_id, day_id) = CURDATE()";
		$getInfo = $db -> prepare($sql);
		$getInfo -> bindParam(":site", $site);
		$getInfo -> execute();
		$infoToday = $getInfo -> fetch();
		
		// Reload with the inserted info into variable
		$sql = "SELECT view_getCounter.*, sum(counter_values.all_value)
			FROM view_getCounter LEFT JOIN counter_values ON view_getCounter.site = counter_values.site 
	    	WHERE view_getCounter.site=:site";
		$stats = $db -> prepare($sql);
		$stats -> bindParam(":site", $site);		
		$statsInfo = $stats -> fetch();
		$ignore = true;
	}

	$day_value = $infoToday['day_value'];
	$day_id = $infoToday['day_id'];	
	$month_id = $infoToday['month_id'];
	$year_id = $infoToday['year_id'];
	$recorded_site = $infoToday['site'];
	// If its the first time, display starting values in the webform
	// else use the values from DB
	$all_value = (isset($statsInfo['all_value']))?  $statsInfo['all_value'] : 1;
	$yesterday_value = (isset($statsInfo['yesterDay']))? $statsInfo['yesterDay'] : 0;
	$this_year_value = (isset($statsInfo['thisYear']))? $statsInfo['thisYear'] : 1;
	$this_week_value = (isset($statsInfo['thisWeek']))? $statsInfo['thisWeek'] : 1;
	$twolast_weeks_value = (isset($statsInfo['twoWeekBack']))? $statsInfo['twoWeekBack'] : 1;
	$this_month_value = (isset($statsInfo['lastMonth']))? $statsInfo['lastMonth'] : 1;
	$record_date =  (isset($statsInfo['record_date']))? $statsInfo['record_date'] : date("Y-m-d");
	$record_value = (isset($statsInfo['recordInOneDay']))? $statsInfo['recordInOneDay'] : 1;
	
	$res -> closeCursor();
	// Check Ignore Lists
	// Check Ignore Browser Agents
	$length = sizeof($counter_ignore_agents);
	for ($i = 0; $i < $length; $i++){
		if (substr_count($counter_agent, strtolower($counter_ignore_agents[$i]))){
			$ignore = true;
			break;
		}
	}	 
	// Check Ignore IP
	$length = sizeof($counter_ignore_ips);
	for ($i = 0; $i < $length; $i++){
		if ($counter_ip == $counter_ignore_ips[$i]){
			$ignore = true;
			break;
		}
	}
	// Check Ignore Site
	$length = sizeof($count_ignore_sites);
	for($i = 0; $i < $length; $i++){
		if(substr_count($recorded_site,strtolower($count_ignore_sites[$i]))){
			$ignore = true;
			break;
		}
	}

	// Delete IP's that have been "locked" for $counter_expire seconds
	if ($ignore == false){
		$sql = "DELETE FROM counter_ips WHERE unix_timestamp(NOW())-unix_timestamp(visit) >= :counterExpire";
		$res = $db -> prepare($sql);
		$res -> bindParam(":counterExpire", $counter_expire);
		$res -> execute();
		$res -> closeCursor();
	}
	// Look up that if the ip have been here before and if so update the expire time, If not insert a new "ipLock"
	if ($ignore == false){
		$sql = "UPDATE counter_ips SET visit = NOW() WHERE ip=:counterIp AND site=:site";
		$res = $db -> prepare($sql);
		$res -> bindParam(":counterIp", $counter_ip);
		$res -> bindParam(":site", $site);
		$res -> execute();
		if($res -> rowcount() > 0){
			$ignore = true;
		}else{
			// Insert IP to table
			$db -> beginTransaction();
			$sql = "INSERT INTO counter_ips (ip, site, visit) VALUES (:counterIp, :site, NOW())";
			$res = $db -> prepare($sql);
			$res -> bindParam(":counterIp", $counter_ip);
			$res -> bindParam(":site", $site);
			$res -> execute();
			if ($res -> rowCount() == 0){
				$db -> rollback();
				throw new Exception('Error inserting IP to CounterIP');
			}
			$db -> commit();
		}
	}
	
	// How many is on this site right now?
	$sql = "SELECT count(*) FROM counter_ips WHERE site=:site";
	$res = $db -> prepare($sql);
	$res -> bindParam(":site", $site);
	$res -> execute();
	$online = $res -> fetch();
	$online=$online[0];
	$res -> closeCursor();
	
	// If this is a new IP or an IP that havent been here for $counterExpire then increment values
	if ($ignore == false){
		// This day
		if ($day_id == date("j")){
			$day_value++;
		}else{
			$day_value = 1;
			$day_id = date("j");
		}
	   
		//  This Month
		if ($month_id != date("n")){
			$month_id = date("n");
	  	}
	 
		//  This Year
		if ($year_id != date("Y")){
			$year_id = date("Y");
	  	}
	  	// Sets new record on total views on one day and date
	  	if ($day_value > $record_value){
			$record_value = $day_value;
			$record_date = date("Y-m-d H:i:s");
	  	}    	
	     // Updates number of views on this site
	    $sql = "UPDATE counter_values SET day_id =:day_id, day_value =:day_value,
	      month_id =:month_id, year_id =:year_id, all_value= all_value + 1, 
	      record_date =:record_date, record_value =:record_value WHERE site =:site AND day_id =:day_id AND 
	      month_id =:month_id AND year_id =:year_id";
	    $res = $db -> prepare($sql);
	    $res -> bindParam(":day_id", $day_id);
	    $res -> bindParam(":day_value", $day_value);
	    $res -> bindParam(":month_id", $month_id);
	    $res -> bindParam(":year_id", $year_id);
	    $res -> bindParam(":record_date", $record_date);
	    $res -> bindParam(":record_value", $record_value);   
	    $res -> bindParam(":site", $site);
	    $res -> execute();
	    $res = NULL;
	    // Get the correct count values from DB
	    $sql = "SELECT view_getCounter.*, sum(counter_values.all_value) as all_value
			FROM view_getCounter LEFT JOIN counter_values ON view_getCounter.site = counter_values.site 
	    	WHERE view_getCounter.site=:site";
     	$result = $db -> prepare($sql);
     	$result -> bindParam(":site", $site);
     	$result -> execute();
     	$statsInfo = $result -> fetch();
     	$yesterday_value = $statsInfo['yesterDay'];
     	$this_year_value = $statsInfo['thisYear'];
     	$this_week_value = $statsInfo['thisWeek'];
     	$twolast_weeks_value = $statsInfo['twoWeekBack'];
     	$this_month_value = $statsInfo['lastMonth'];
     	$record_date =  $statsInfo['record_date'];
     	$record_value = $statsInfo['recordInOneDay'];
     	$all_value = $statsInfo['all_value'];
	     	
	}
//Show views stats for this site
	echo "<div class='counterVisiors'>
		<div id='stattop'>
			<img src='include/img/counter.gif' width='16' height='16' /> Visninger på innlegget:
		</div>
		<div id='statbody'>
			<ul>
			 <li><b>{$online}</b> Er på denne siden</li>
			 <li><b>{$day_value}</b> I dag</li>
			 <li><b>{$yesterday_value}</b> I går</li>
			 <li><b>{$this_week_value}</b> Denne uken</li>
			 <li><b>{$twolast_weeks_value}</b> Siste 14 dager</li>
			 <li><b>{$this_month_value}</b> Denne måneden</li>
			 <li><b>{$this_year_value}</b> Dette året</li>
			 <li><b>{$all_value}</b> Totalt</li>
			</ul>
		</div>
		<div id='statfooter'>
			Rekord: {$record_value} (".date("d.m.Y", strtotime($record_date)).")
		</div>
	</div>"; 
}
/**
 * Gets different stats for the blogs based om user input and prints the result to an html-table
 * @param Obj $db PDO database object
 * @param string $postedStart from date for publish date on post
 * @param string $postedStop  to date for publish date on post
 * @param int $num number of results to display (default 10)
 * @param string $type [views(default)|users|comments]
 * @param string $userName user name to look for
 * @param string $postTitle title to look for
 * @param string $period [week|twoweeks|month|alltime(default)]
 *  
 */
function getGlobalStats($db, $postedStart, $postedStop, $num, $type, $userName, $postTitle, $period){
	$postedStart = $postedStart .= " 00:00:00"; // Add times for using in SQL
	$postedStop = $postedStop .= " 23:59:59";
	
	if(empty($postTitle)){        		// Prepare stings for using with search:
		$postTitle = "%";
	}else{
		$postTitle = "%$postTitle%";
	}
	if(empty($userName)){
		$userName = "%";
	}else{
		$userName = "%$userName%";
	}
	
	switch ($type){
	// IF STATISTICS FOR VIEWS IS CHOOSEN
		case'views':
			switch ($period) {
				case 'week':
					$period = 'thisWeek';
					break;
				case 'twoweek':
					$period = 'twoWeekBack';
					break;
				case 'month':
					$period = 'lastMonth';
					break;
				case 'alltime':
					$period = 'all_value';
					break;
			}
			$sql ="SELECT view_getCounter.$period AS views, author, postTitle, postId
					FROM view_getCounter
					JOIN post ON post.postid = view_getCounter.siteId
					LEFT JOIN user ON post.author = user.username
					WHERE post.timecreated BETWEEN :start AND :stop AND user.isblocked = 0 AND post.statusCode NOT LIKE 'D%'";
					$sql .=" AND post.postTitle LIKE :postid ";
					$sql .=" AND user.username LIKE :user ";
					$sql .="ORDER BY views DESC LIMIT :num";
		
			$result = $db -> prepare($sql);
			$result -> bindParam(":stop", $postedStop);
			$result -> bindParam(":start", $postedStart);
			$result -> bindValue(":num", (int) $num, PDO::PARAM_INT);
			$result -> bindParam(":user", $userName);
			$result -> bindParam(":postid", $postTitle);
			$result -> execute();
			echo "<table id='stattable'>";
			echo "<tr><th>Tittel</th><th>Forfatter</th><th>Antall visninger</th></tr>";
			$i = 1;
			while($res = $result ->  fetch(PDO::FETCH_ASSOC)){
				echo ($i % 2)? "<tr>":"<tr class='alt'>";
				echo "<td><a href='showPost.php?id={$res['postId']}'>{$res['postTitle']}</a></td>
				<td><a href='displayUsr.php?usrName={$res['author']}'>{$res['author']}</a></td>
				<td class='num'>{$res['views']}</td>";
				$i++;
			}
			echo "</table>";
			break;
	// IF STATISTICS FOR USER IS CHOOSEN
		case 'users':
				switch ($period) {
					case 'week':
						$period = 'thisWeek';
						break;
					case 'twoweek':
						$period = 'twoWeekBack';
						break;
					case 'month':
						$period = 'lastMonth';
						break;
					case 'alltime':
						$period = 'all_value';
						break;
				}
				$sql = "SELECT COUNT(postId) AS antpost, SUM(view_getCounter.$period) AS views, user.username
					FROM post
					LEFT OUTER JOIN view_getCounter  ON post.postid = view_getCounter.siteId
					LEFT JOIN user ON post.author = user.username
					WHERE post.timecreated BETWEEN :start AND :stop AND user.isblocked = 0 AND post.statusCode NOT LIKE 'D%'";
					$sql .=" AND post.postTitle LIKE :postid ";
					$sql .=" AND user.username LIKE :user ";
					$sql .=" GROUP BY user.username
							 ORDER BY views DESC
							 LIMIT :num";
				$result = $db -> prepare($sql);
				$result -> bindParam(":stop", $postedStop);
				$result -> bindParam(":start", $postedStart);
				$result -> bindValue(":num", (int) $num, PDO::PARAM_INT);
				$result -> bindParam(":user", $userName);
				$result -> bindParam(":postid", $postTitle); 
				$result -> execute();
				echo "<table id='stattable'>";
				echo "<tr><th>Forfatter</th><th>Antall visninger</th><th>Antall innlegg</th></tr>";
				$i = 1;
				while($res = $result ->  fetch(PDO::FETCH_ASSOC)){
					echo ($i % 2)? "<tr>":"<tr class='alt'>";
					echo "<td><a href='displayUsr.php?usrName={$res['username']}'>{$res['username']}</a></td>
					<td class='num'>{$res['views']}</td>
					<td class='num'>{$res['antpost']}</td>
					</tr>";
					$i++;
					}
					echo "</table>";
				break;
	// IF STATISTICS FOR COMMENTS IS CHOOSEN		
		case 'comments':
				switch ($period) {
					case 'week':
						$period = ' AND c.published >= (NOW() - INTERVAL 1 WEEK) ';
						break;
					case 'twoweek':
						$period = ' AND c.published >= (NOW() - INTERVAL 2 WEEK) ';
						break;
					case 'month':
						$period = ' AND c.published >= (NOW() - INTERVAL 1 MONTH) ';
						break;
					case 'alltime':
						$period = '';
						break;
				}
				$sql = "SELECT COUNT(c.comment) AS antcom, p.author, p.postTitle, c.postId
						FROM comments AS c, post AS p, user AS u
						WHERE p.timecreated BETWEEN :start AND :stop  AND p.postId=c.postId
						AND p.author = u.username AND u.isblocked = 0
						AND c.commentStatus NOT LIKE 'CD%' AND p.statusCode NOT LIKE 'D%'";
						$sql .= $period;		
						$sql .=" AND p.postTitle LIKE :postid";
						$sql .=" AND p.author LIKE :user";	
						$sql .=" GROUP BY c.postId ORDER BY antcom DESC LIMIT :num";	
					$result = $db -> prepare($sql);
					$result -> bindParam(":stop", $postedStop);
					$result -> bindParam(":start", $postedStart);
					$result -> bindValue(":num", (int) $num, PDO::PARAM_INT);
					$result -> bindParam(":user", $userName);
					$result -> bindParam(":postid", $postTitle); 
					$result -> execute();
					echo "<table id='stattable'>";
					echo "<tr><th>Tittel</th><th>Forfatter</th><th>Kommentarer</th></tr>";
					$i = 1;
					while($res = $result ->  fetch(PDO::FETCH_ASSOC)){
						echo ($i % 2)? "<tr>":"<tr class='alt'>";
						echo "<td><a href='showPost.php?id={$res['postId']}'>{$res['postTitle']}</a></td>
						<td><a href='displayUsr.php?usrName={$res['author']}'>{$res['author']}</a></td>
						<td class='num'>{$res['antcom']}</td>
						</tr>";
						$i++;
					}
					echo "</table>";				
				break;
	}
}

?>
